package br.edu.ifrn.potigol.tester;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;

public class Tester {
	private String bin;
	private String pattern;
	private String dir;
	private int total;
	private HashMap<String, String> failures;

	private Tester(String bin, String pattern, String dir) {
		this.bin = bin;
		this.pattern = pattern;
		this.dir = dir;
		this.total = 0;
		this.failures = new HashMap<String, String>();
		try {
			run();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void run() throws IOException {
		File testDir = new File(dir);
		
		FilenameFilter ffilter = new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return name.endsWith(pattern);
			}
		};
		
		for (File file: testDir.listFiles(ffilter)) {
			FileReader freader = null;
			try {
				freader = new FileReader(file);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			BufferedReader reader = new BufferedReader(freader);
			
			String line = null;
			String expected = "";
			String actual = "";
			while ((line = reader.readLine()) != null)
				if (line.indexOf("=>") != -1) {
					String t = line.substring(line.indexOf("=>") +2, line.length()).trim();
					
					if (!t.equals("")) expected += t.concat(" | ");
				}
			
			actual += test(file);
		
			if (expected.equals(actual)) 
				pass();
			else
				fail(file, expected, actual);
			
			reader.close();
			freader.close();
		}
		
		for (String file: failures.keySet()) {
			System.out.print("\n" + file);
			System.out.print("\n" + failures.get(file) + "\n");
		}
		
		System.out.println("\nTestes: " +  total + "; Falhas: " + failures.size() + ".");
	}
	
	private String test(File file) {		
		String result = "";
		try {
			Process process = Runtime.getRuntime().exec(bin + " " + file.getPath());
			BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
		    String inputLine = null;
			while ((inputLine = in.readLine()) != null) {
		    	result += inputLine.concat(" | ");
		    }
		    in.close();
		} catch (IOException e) {
		    e.printStackTrace();
		}
		
		return result;
	}
	
	private void pass() {
		++total;
		System.out.print(".");
	}
	
	private void fail(File file, String expected, String actual) {
		++total;
		failures.put("[" + file.getPath() + "]", "\tEsperado: " + expected + "\n\tRecebido: " + actual);
		System.out.print("F");
	}
	
	public static void main(String[] args) {
		new Tester("run/potigol", ".poti", "test");
	}
}
